<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      class="flex flex-wrap -mb-15px"
      label-width="105px"
    >
      <el-col :span="6">
        <el-form-item label="指纹名称" prop="name">
          <ns-input
            v-model="queryParams.name"
            class="!w-full"
            clearable
            placeholder="请输入指纹名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-row :gutter="10">
          <el-col :span="16">
            <el-form-item label="文件指纹" prop="type">
              <el-select class="!w-full" placeholder="请选择指纹类型" v-model="queryParams.type">
                <el-option
                  v-for="item in types"
                  :label="item.name"
                  :value="item.name"
                  :key="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="" prop="typeValue" class="typeValue-form-item">
              <ns-input
                v-model="queryParams.typeValue"
                class="!w-full"
                clearable
                placeholder="请输入指纹内容"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>

      <el-col :span="6">
        <el-form-item label="归属机构" prop="deptId">
          <el-cascader
            v-model="queryParams.deptId"
            clearable
            class="!w-full"
            placeholder="请选择归属机构"
            :options="options"
            :props="cascaderProps"
            filterable
            :filter-method="sysFilterMethod"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="归属系统" prop="systemId">
          <el-cascader
            v-model="queryParams.systemId"
            placeholder="请选择归属系统"
            class="!w-full"
            :props="systemCascaderProps"
            :options="systemList"
            filterable
            clearable
            :filter-method="sysFilterMethod"
        /></el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="数据保护标准" prop="standard">
          <el-select
            v-model="queryParams.standard"
            class="!w-full"
            clearable
            placeholder="请选择数据保护标准"
          >
            <el-option
              v-for="item in markedTemplateInfo"
              :label="item.dataStandardName"
              :value="item.id"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="分类" prop="classification">
          <el-cascader
            class="!w-full"
            v-model="queryParams.classification"
            placeholder="请选择分类"
            :props="classificationCascaderProps"
            :options="classificationList"
            filterable
            clearable
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="分级" prop="level">
          <el-select v-model="queryParams.level" class="!w-full" clearable placeholder="请选择分级">
            <el-option
              v-for="(level, levelIndex) in levelList"
              :key="levelIndex"
              :label="level.levelName"
              :value="level.levelCode"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="更新时间" prop="daterange">
          <el-date-picker
            class="!w-full"
            v-model="queryParams.daterange"
            :editable="false"
            clearable
            type="daterange"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="text-right">
        <el-button @click="handleQuery" v-hasPermi="['develop:featureLibrary:search']">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery" v-hasPermi="['develop:featureLibrary:search']">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-col>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <div class="handle-btns">
      <el-button
        type="primary"
        @click="openForm('create')"
        v-hasPermi="['develop:featureLibrary:add']"
        >新增（文件提取）</el-button
      >
      <el-button @click="handleImport" v-hasPermi="['develop:featureLibrary:import']">
        新增（指纹提取）</el-button
      >
      <el-button @click="handleQuote" v-hasPermi="['develop:featureLibrary:quote']">
        引用</el-button
      >
      <el-button @click="handleSynchronous" v-hasPermi="['develop:featureLibrary:sync']">
        同步</el-button
      >
      <el-button @click="handleExport" v-hasPermi="['develop:featureLibrary:export']">
        导出</el-button
      >
      <el-button type="danger" @click="delList" v-hasPermi="['develop:featureLibrary:delete']">
        删除
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="list"
      ref="treeTableRef"
      row-key="id"
      show-overflow-tooltip
      border
      @selection-change="selectChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="80" label="序号" align="center" />
      <el-table-column prop="name" label="指纹名称" align="center" />
      <!-- <el-table-column width="300" label="指纹类型" align="center">
        <template #default="scope">
          {{ getTypeName(scope.row.type) }}
        </template>
      </el-table-column> -->
      <el-table-column
        label="文件指纹"
        align="center"
        :formatter="(row) => renderFinger({ row })"
      />
      <el-table-column prop="deptName" label="归属机构" align="center" />
      <el-table-column prop="systemName" label="归属系统" align="center" />
      <el-table-column prop="standardName" label="数据保护标准" align="center" />
      <el-table-column
        prop="classification"
        label="分类"
        align="center"
        :formatter="(row) => renderClassification({ row })"
      />
      <el-table-column
        prop="level"
        label="分级"
        align="center"
        :formatter="(row) => renderLevel({ row })"
      />
      <el-table-column prop="updateTime" width="300" label="更新时间" align="center" />
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            :disabled="scope.row.fileFrom !== 3"
            v-hasPermi="['develop:featureLibrary:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            :disabled="scope.row.fileFrom !== 3"
            v-hasPermi="['develop:featureLibrary:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.page"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 表单弹窗：添加/修改 -->
  <FingerprintForm ref="formRef" @success="getList" />
  <ImportForm ref="importFormRef" @success="getList" />
  <QuoteForm ref="quoteFormRef" @success="getList" />
  <FileChose ref="fileChoseRef" @success="openFileChose" />
  <SynchronousDialog ref="synchronousDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { sysFilterMethod } from '@/utils/selectFilter'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { handleTree } from '@/utils/tree'
import { levelPage } from '@/api/strategyManage/level/index'
import { dataClassificationTree } from '@/api/dataStandards/classification/index'
import { Plus, Top, Bottom } from '@element-plus/icons-vue'
import ImportForm from './formDialog/ImportForm.vue'
import QuoteForm from './formDialog/QuoteForm.vue'
import FileChose from './formDialog/FileChose.vue'
import SynchronousDialog from './formDialog/SynchronousDialog.vue'
import {
  getFingerPage,
  deleteFinger,
  deleteFingerList,
  getFingerType,
  fingerExportExcelFile
} from '@/api/develop/featureLibrary/fingerprint'
import FingerprintForm from './formDialog/FingerprintForm.vue'
import type { FormType } from './formDialog/FingerprintForm.vue'
import download from '@/utils/download'
import { ElTable } from 'element-plus'

import { renderFinger, renderClassification, renderLevel } from '@/utils/commonRender'

const treeTableRef = ref<InstanceType<typeof ElTable>>()
const { proxy } = getCurrentInstance() as any
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const queryFormRef = ref() // 搜索的表单
const total = ref(10) // 列表的总页数
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: undefined,
  type: undefined,
  typeValue: undefined,
  systemId: undefined,
  deptId: undefined,
  standard: undefined,
  level: undefined,
  classification: undefined,
  daterange: ['', ''] as [string, string]
})

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 暴露方法 */
defineExpose({
  resetQuery
})

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof FingerprintForm>>()
const openForm = (type: FormType, id?: number) => {
  formRef.value?.open(type, id)
}
/** 查询列表 */
const getList = async () => {
  loading.value = true

  const params = {} as Record<string, any>

  if (queryParams.type && queryParams.typeValue) {
    params[queryParams.type] = queryParams.typeValue
  }

  if (queryParams.daterange !== null && queryParams.daterange[0] && queryParams.daterange[1]) {
    params.updateTime = queryParams.daterange
      .map((item, index) => {
        const str = index === 0 ? ' 00:00:00' : ' 23:59:59'
        return item + str
      })
      .join(',')
  }

  try {
    const { count, data } = await getFingerPage({
      ...params,
      ...toRaw(queryParams),
      daterange: undefined
    })
    list.value = data
    total.value = count
  } finally {
    loading.value = false
  }
}

const ids = ref([])
const selectChange = (e) => {
  ids.value = e.map((item) => item.id)
}

/** 删除按钮操作 */
const delList = () => {
  if (ids.value.length > 0) {
    proxy.$modal
      .confirm(`确定要删除所选数据吗？`)
      .then(async () => {
        await deleteFingerList(ids.value)
        ElMessage.success('删除成功')
        await getList()
      })
      .catch(() => {})
  } else {
    proxy.$modal
      .confirm(`未勾选时删除查询条件下所有数据`)
      .then(async () => {
        const allIds = list.value.map((item) => {
          return item.id
        })
        await deleteFingerList(allIds)
        ElMessage.success('删除成功')
        await getList()
      })
      .catch(() => {})
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteFinger(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const types = ref<
  {
    name: string
    value: string
  }[]
>([])

/** 获取指纹类型 */
async function getTypes() {
  const res = await getFingerType()
  types.value = Object.entries(res).map(([key, value]) => {
    return {
      name: value as string,
      value: key
    }
  })
}

/** 获取type名称 */
// function getTypeName(key) {
//   return types.value.find((item) => item.value === key)?.name || ''
// }

const systemList = ref()
const options = ref()
const markedTemplateInfo = ref()
const levelList = ref<any[]>([])
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  options.value = data
}
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  levelList.value = data
}

// 分类下拉
const classificationList = ref<any[]>([])
const getClassificationList = async () => {
  const data = await dataClassificationTree()
  classificationList.value = traverseTree(data)
}
function traverseTree(data) {
  const updatedTree = [] as any[]
  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.pid == '-1') {
      node.disabled = true
    }
    updatedTree.push(node)
    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }
  return updatedTree
}

const exportLoading = ref(true)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()

    const params = {} as Record<string, any>

    if (queryParams.type && queryParams.typeValue) {
      params[queryParams.type] = queryParams.typeValue
    }

    const ids = treeTableRef.value?.getSelectionRows().map((row) => row.id)
    // 发起导出
    exportLoading.value = true
    const data = await fingerExportExcelFile({ ...params, ids, ...toRaw(queryParams) })
    download.excel(data, '指纹库导出.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

const quoteFormRef = ref()
const fileChoseRef = ref()
const synchronousDialogRef = ref()
const handleQuote = () => {
  fileChoseRef.value.open()
}

// 获得选取的引入文件并且打开引用界面
const openFileChose = (data) => {
  quoteFormRef.value.open(data)
}

// 同步
const handleSynchronous = () => {
  synchronousDialogRef.value.open()
}
onMounted(async () => {
  await getTypes()
  getList()

  getSystemList()
  getDeptList()
  dataStandardsPage({ page: 1, pageSize: 10000, status: '1' }).then((res) => {
    markedTemplateInfo.value = res.data
  })
  getLevelList()
  getClassificationList()
})
</script>

<style lang="scss" scoped>
.handle-btns {
  margin-bottom: 20px;
}
.typeValue-form-item {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style>
